#!/usr/bin/perl -w

use strict;
use warnings;
use Geo::IP;
use Data::Dumper;

my $location;
my %IPtoGeo;
my %IPCounter;
my $ip;
my $gi = Geo::IP->open("/usr/share/GeoIP/GeoLiteCity.dat", GEOIP_MEMORY_CACHE);
my $record;
my $kml;
my $myip = `/usr/bin/wget -qO- www.whatismyip.org`;



open LOG, "/var/log/squid3/access.log.custom" or die $!;
while (<LOG>)
{
	($ip)=split(/ /,$_,2);
	chomp $ip;
	if ($ip ne "-" and $record = $gi->record_by_addr($ip))
	{
		if (!(exists $IPtoGeo{$ip}))
		{
			$IPtoGeo{ $ip } = $record->longitude.",".$record->latitude;
		}
		$IPCounter{ $ip }++;
	}
	else
	{
	print "algo casca en squid\n";
	}
}




$kml=qq(<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Folder>
    <name>WebServers</name>
    <description>Que sera q sera...</description>
    <Style id="yellowLineGreenPoly">
      <LineStyle>
        <color>7f0ff0ff</color>
        <width>2</width>
      </LineStyle>
    </Style>

);

my $mylocation;
	if ($record=$gi->record_by_addr($myip))
{
$mylocation = $record->longitude.",".$record->latitude;
         $kml .= qq(
	<Placemark>
	<name>Yo @ $myip!!</name>
	<description>Where things live...</description>
	<Point>
	<coordinates>$mylocation</coordinates>
	</Point>
	</Placemark>
	);
}

$kml .="\n";

      foreach $ip (keys %IPtoGeo){

         $kml .= qq(
	<Placemark>
	<name>$ip</name>
	<description>$ip Cont=$IPCounter{$ip}</description>
	<Point>
	<coordinates>$IPtoGeo{$ip}</coordinates>
	</Point>
	</Placemark>
	 <Placemark>
      <name>$myip-$ip</name>
      <description></description>
      <styleUrl>#yellowLineGreenPoly</styleUrl>
      <LineString>
        <tessellate>1</tessellate>
        <coordinates> 
		$IPtoGeo{$ip}
		$mylocation
        </coordinates>
      </LineString>
    </Placemark>
	);
	}


	$kml .="\n";
	$kml .=qq(
	</Folder>
	</kml>
	);
open DEST, ">", "/tmp/temp.kml" or die $!;
print DEST $kml;
close DEST;
close LOG;



print Dumper(\%IPtoGeo);
print "\n\n";
print Dumper(\%IPCounter);
